package com.lqs.dataservice.Service;

import cn.hutool.core.util.StrUtil;
import com.lqs.dataservice.constants.MessageConstants;
import com.lqs.dataservice.dao.UserDao;
import com.lqs.dataservice.entity.User;
import com.nip.db.mongodb.utils.tips.Response;
import com.nip.db.mongodb.utils.tips.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * UserService
 *
 * @author < a href=" ">BBB</ a>
 * @version v1.0.01
 * @date 2019-12-27 16:47
 */
@Service
public class UserService {
  @Autowired
  UserDao userDao;

  public List<User> findAllUser() {
    return userDao.findAll();
  }

  public User findUserById(String id) {
    return userDao.findById(id).orElse(null);
  }

  public User findUserByCode(String code) {
    return userDao.findAllByCode(code).get(0);
  }

  public Response deleteUsers(List<String> ids){
    userDao.deleteAllByIdIn(ids);
    return new Response(ResponseCode.CODE_200,MessageConstants.SUCCESS);
  }

  /*
  * 登录
  * */

  public Response login(String code,String password){
    User user = userDao.findUserByCode(code);
    if(StringUtils.isEmpty(user)){
      return new Response(ResponseCode.CODE_500,"账号错误");
    }
    if(!password.equals(user.getPassword())){
      return new Response(ResponseCode.CODE_500,"密码错误");
    }
    return new Response(ResponseCode.CODE_200,MessageConstants.SUCCESS,user);
  }

  public Response saveUser(User entity) {
    try {
     if (StrUtil.isEmpty(entity.getId())){
       entity.setPassword("123456");
       userDao.save(entity);
       return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
     }else {
       User user = userDao.findAllByCode(entity.getCode()).get(0);
       if (StringUtils.isEmpty(user)||user.getId().equals(entity.getId())){
         userDao.save(entity);
         return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
       }else {
         return new Response(ResponseCode.CODE_204,"code重复");
       }
     }
    } catch (Exception e) {
      return new Response(ResponseCode.CODE_202, e.getMessage());
    }
  }

  public Response saveUserPassword(User entity) {
    try {
      userDao.save(entity);
      return new Response(ResponseCode.CODE_200, MessageConstants.SUCCESS);
    } catch (Exception e) {
      return new Response(ResponseCode.CODE_202, e.getMessage());
    }
  }


  public List<User> findAllByUserParentId(String id){
    return userDao.findAllByUserParentId(id);
  }

  public List<User> findAllUserByRemark(String remark){
    return userDao.findAllUserByRemark(remark);
  }

  public List<User> findAllByUserParentIdAndRemark(String id,String remark){
    return userDao.findAllByUserParentIdAndRemark(id,remark);
  }


}
